package club.ruanx.auth.vcode.repository;

import club.ruanx.auth.vcode.ValidateCode;
import club.ruanx.auth.vcode.enumeration.ValidateCodeType;
import club.ruanx.auth.vcode.service.VcodeRedisService;
import club.ruanx.util.ServletContextUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.UUID;

/**
 * @author 阮胜
 * @date 2018/9/30 14:38
 */
public class RedisValidateCodeRepository implements ValidateCodeRepository {
    private static final String VALIDATE_ID = "vid";


    @Autowired
    private VcodeRedisService vcodeRedisService;


    @Override
    public void save(ValidateCode code, ValidateCodeType validateCodeType) {
        String vid = UUID.randomUUID().toString().replace("-", "");
        ServletContextUtils.getCurrentResponse().setHeader(VALIDATE_ID, vid);
        vcodeRedisService.saveValidateCode(vid, code);

    }

    @Override
    public ValidateCode get(ValidateCodeType validateCodeType) {
        String vid = getVid();
        Object vcode = vcodeRedisService.getValidateCode(vid);
        if (vcode == null) {
            return null;
        }
        return (ValidateCode) vcode;
    }

    @Override
    public void remove(ValidateCodeType codeType) {
        vcodeRedisService.deleteValidateCode(getVid());
    }

    private String getVid() {
        return ServletContextUtils.getCurrentRequest().getParameter(VALIDATE_ID);
    }
}
